﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;

public class SearchLightController : SimpleElectricalEquipment
{
    [SerializeField] private float turnSpeed;
    [SerializeField] private Color searchColor;
    [SerializeField] private Color warnColor;

    [Header("射线")]
    [SerializeField] private LayerMask layerMask;

    [Header("旋转")]
    [SerializeField] 
    private Quaternion startAngle;
    [Space]
    [SerializeField] 
    private Quaternion endAngle;

    Quaternion m_targetAngle;

    //旋转角度中值
    float m_midAngle;

    //判断巡逻
    bool m_canSer;
    bool m_findPlayer;
    bool m_onPlayer;
    bool m_patrol;

    GameObject player;
    Light2D light;
    AudioSource audioSource;

    // Start is called before the first frame update
    void Start()
    {
        m_canSer = true;
        m_findPlayer = false;
        m_onPlayer = false;
        m_patrol = true;

        gameObject.transform.rotation = startAngle;
        m_targetAngle = endAngle;
        m_midAngle = Mathf.Abs(endAngle.eulerAngles.z - startAngle.eulerAngles.z) / 2;
        audioSource = GetComponent<AudioSource>();
        audioSource.volume = SaveData._.muiscSize;
    }

    // Update is called once per frame
    void Update()
    {
        SearchOn();
        CheckSearch();
    }

    void SearchOn()
    {
        //gameObject.transform.rotation = Quaternion.Lerp(transform.rotation, targetAngle, turnSpeed*Time.deltaTime);
        //gameObject.transform.rotation = Quaternion.Slerp(transform.rotation, targetAngle, turnSpeed * Time.deltaTime);

        if (gameObject.transform.eulerAngles.z > endAngle.eulerAngles.z)
            gameObject.transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, endAngle.eulerAngles.z);
        else if(gameObject.transform.eulerAngles.z < startAngle.eulerAngles.z)
            gameObject.transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, startAngle.eulerAngles.z);

        if (!m_canSer) return;

        if (m_findPlayer)
        {
            TurnToPlayer();
            return;
        }

        if (!m_patrol)
            return;

        float speedRate = Mathf.Abs(Quaternion.Angle(transform.rotation, m_targetAngle) - m_midAngle)/m_midAngle;
        float speed = turnSpeed - turnSpeed * speedRate/1.2f;

        gameObject.transform.Rotate(0,0, speed * Time.deltaTime);

        if (gameObject.transform.eulerAngles.z >= endAngle.eulerAngles.z || gameObject.transform.eulerAngles.z <= startAngle.eulerAngles.z) 
        {
           turnSpeed *= -1;
        }

        if (Quaternion.Angle(transform.rotation, m_targetAngle)< 1)
        {
            if (m_targetAngle == startAngle)
                m_targetAngle = endAngle;
            else
                m_targetAngle = startAngle;
        }
    }


    public void StopSearch()
    {
        m_canSer = false;
        m_patrol = false;
    }
    
    public void StartSearch()
    {
        m_canSer = true;
        m_patrol = true;
    }

    public void CheckSearch()
    {

        if (!m_canSer)
            return;

        //m_findPlayer = false;
        if(m_patrol == true)
        {
            //foreach (var point in rayPoints)
            //{                   
            //    //Debug.Log(point.position);
            //    m_findPlayer = SetRay(point.position);
            //    if (m_findPlayer)
            //    {
            //        StopSearch();
            //        return;
            //    }
            //}

            m_findPlayer = false;

            if (m_onPlayer && player != null)
            {
                m_findPlayer = SetRay(player.transform.position);
                if (m_findPlayer)
                {
                    //StopSearch();
                    m_patrol = false;
                    return;
                }
            }
        }
        else if(player != null)
        {
            m_findPlayer = SetRay(player.transform.position);
        }
    }

    public bool SetRay(Vector2 target)
    {
        Vector2 direction = new Vector2(target.x-transform.position.x,target.y-transform.position.y);
        Ray2D ray = new Ray2D(transform.position,direction);
        //Debug.Log(transform.position + " " + direction) ;
        Debug.DrawRay(ray.origin, direction, Color.green, 0.2f);

        RaycastHit2D rayInfo = Physics2D.Raycast(ray.origin, ray.direction,Vector2.Distance(target,transform.position) ,layerMask);

        //RaycastHit2D rayInfo = Physics2D.Linecast(ray.origin, ray.direction,layerMask);
        
        if (rayInfo.collider != null)
        {
            //sDebug.Log(rayInfo.collider+" "+rayInfo.distance);
            if ( rayInfo.collider.tag.Equals(TagAndLayersConfigs.Tag.Player) || rayInfo.collider.tag.Equals(TagAndLayersConfigs.Tag.Bird))
            {              
                player = rayInfo.collider.gameObject;            
                return true;
            }        
        }     
        return false;
    }

    public void TurnToPlayer()
    {
        if (player != null)
        {
            Vector2 diretion = player.transform.position - transform.position;
            float angle = Mathf.Atan2(diretion.y, diretion.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, angle), Mathf.Abs(turnSpeed) / 20 * Time.deltaTime);
        }
          
    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        

        if (collision.tag.Equals(TagAndLayersConfigs.Tag.Player) && m_findPlayer ||collision.tag.Equals(TagAndLayersConfigs.Tag.Bird) && m_findPlayer)
        {
            m_onPlayer = true;
            light.color = warnColor;
            EventManager.Invoke(EventNameConfig.GanmeEnd.PlayerInEndLight,player.transform);
            if (audioSource!=null)
            {
                if (!audioSource.isPlaying)
                {
                    audioSource.Play();
                }
                
            }
        }
        else if (collision.tag.Equals(TagAndLayersConfigs.Tag.Player)&&!m_findPlayer || collision.tag.Equals(TagAndLayersConfigs.Tag.Bird) && !m_findPlayer)
        {
            m_onPlayer = true;
            player = collision.gameObject;
            light.color = searchColor;
            //m_canSer = true;

            m_patrol = true;
            EventManager.Invoke(EventNameConfig.GanmeEnd.PlayerOutEndLight,player.transform);
            if (audioSource != null)
            {
                audioSource.Stop();
            }
        }

    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.tag.Equals(TagAndLayersConfigs.Tag.Player))
        {
            m_onPlayer = false;
            player = collision.gameObject;
            light.color = searchColor;
            //m_canSer = true;
            m_patrol = true;
            EventManager.Invoke(EventNameConfig.GanmeEnd.PlayerOutEndLight, player.transform);
            if (audioSource != null)
            {
                audioSource.Stop();
            }
        }
        if (collision.tag.Equals(TagAndLayersConfigs.Tag.Bird))
        {
            m_onPlayer = false;
            player = collision.gameObject;
            light.color = searchColor;
            //m_canSer = true;
            m_patrol = true;
            EventManager.Invoke(EventNameConfig.GanmeEnd.PlayerOutEndLight, player.transform);
            if (audioSource != null)
            {
                audioSource.Stop();
            }
        }
        
    }

    #region 开关控制
    float inte;

    public override void Awake()
    {
        light = gameObject.transform.GetChild(0).GetComponent<Light2D>();
        inte = light.intensity;
        base.Awake();
    }
    public override void Close()
    {
        StopSearch();
        light.intensity = 0;
    }

    public override void Open()
    {
        StartSearch();
        light.intensity = inte;
    }
    #endregion

}
